//https://www.cnblogs.com/zhujiabin/p/7139644.html
package com.hty.filetrans;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class SocketManager {
    private ServerSocket server;
    private Handler handler;

    public SocketManager (Handler handler) {
        this.handler = handler;
        int port = 9999;
        while (port > 9000) {
            try {
                server = new ServerSocket(port);
                break;
            } catch (Exception e) {
                port--;
            }
        }
        sendMessage(1, port);
        Thread receiveFileThread = new Thread(new Runnable(){
            @Override
            public void run() {
                while (true) {
                    receive();
                }
            }
        });
        receiveFileThread.start();
    }

    void sendMessage (int what, Object obj) {
        if (handler != null) {
            Message.obtain(handler, what, obj).sendToTarget();
        }
    }

    void receive() {
        try {
            Socket socket = server.accept();
            String IP = socket.getRemoteSocketAddress().toString();
            InputStream IS = socket.getInputStream();
            InputStreamReader ISR = new InputStreamReader(IS);
            BufferedReader BR = new BufferedReader(ISR);
            String s = BR.readLine();
            BR.close();
            ISR.close();
            IS.close();
            socket.close();
            JSONObject JSONO = new JSONObject(s);
            String type = JSONO.getString("type");
            if (type.equals("text")) {
                String message = JSONO.getString("message");
                sendMessage(0, "[" + IP + "]: " + message);
            } else if (type.equals("file")) {
                String fileName = JSONO.getString("fileName");
                long lastModified = JSONO.getLong("lastModified");

                Socket data = server.accept();
                InputStream dataStream = data.getInputStream();
                sendMessage(0, "接收[" + IP + "]: " + fileName);
                String savePath = Environment.getExternalStorageDirectory().getPath() + File.separator + fileName;
                FileOutputStream FOS = new FileOutputStream(savePath, false);
                byte[] buffer = new byte[1024];
                int size;
                while ((size = dataStream.read(buffer)) != -1) {
                    FOS.write(buffer, 0, size);
                }
                FOS.close();
                dataStream.close();
                data.close();
                File file = new File(savePath);
                boolean b = file.setLastModified(lastModified);
                sendMessage(0, "接收完成：" + fileName + "，修改时间：" + lastModified + "，" + b);
                sendMessage(3, savePath);
            }
        } catch (Exception e) {
            sendMessage(0, "接收错误：" + e.getMessage());
        }
    }

    public void sendText (String message, String IP, int port) {
        try {
            Socket socket = new Socket(IP, port);
            OutputStream OS = socket.getOutputStream();
            OutputStreamWriter OSW = new OutputStreamWriter(OS);
            BufferedWriter BW = new BufferedWriter(OSW);
            JSONObject JSONO = new JSONObject();
            JSONO.put("type", "text");
            JSONO.put("message", message);
            String s = JSONO.toString();
            BW.write(s);
            BW.close();
            OSW.close();
            OS.close();
            socket.close();
            sendMessage(0, "发送：" + s);
        } catch (Exception e) {
            sendMessage(0, "发送错误：" + e.getMessage());
        }
    }

    public void sendFile (ArrayList<String> fileName, ArrayList<String> path, String IP, int port) {
        try {
            for (int i=0; i<fileName.size(); i++) {
                Socket name = new Socket(IP, port);
                OutputStream outputName = name.getOutputStream();
                OutputStreamWriter outputWriter = new OutputStreamWriter(outputName);
                BufferedWriter bwName = new BufferedWriter(outputWriter);
                JSONObject JSONO = new JSONObject();
                JSONO.put("type", "file");
                JSONO.put("fileName", fileName.get(i));
                File file = new File(path.get(i));
                JSONO.put("lastModified", file.lastModified());
                bwName.write(JSONO.toString());
                bwName.close();
                outputWriter.close();
                outputName.close();
                name.close();

                Socket data = new Socket(IP, port);
                OutputStream outputData = data.getOutputStream();
                FileInputStream FIS = new FileInputStream(path.get(i));
                int lfis = FIS.available();
                sendMessage(0, "正在发送：" + fileName.get(i) + "，" + lfis);
                sendMessage(4, lfis);
                int size, length=0;
                byte[] buffer = new byte[1024];
                while ((size = FIS.read(buffer, 0, 1024)) != -1) {
                    outputData.write(buffer, 0, size);
                    length += size;
                    sendMessage(5, length);
                }
                outputData.close();
                FIS.close();
                data.close();
                sendMessage(0, "发送完成：" + fileName.get(i));
            }
            sendMessage(0, "所有文件发送完成");
            sendMessage(6, "");
        } catch (Exception e) {
            sendMessage(0, "发送错误：" + e.getMessage());
        }
    }
}